package service

import (
	"dynamic-private/pkg/base"
	"dynamic-private/pkg/dto"
	"dynamic-private/pkg/po"
	"dynamic-private/pkg/vo"
	"errors"
	"xorm.io/builder"
)

//service命名与文件名保持一致

type dynamicService struct{}

var DynamicService = new(dynamicService)

/*
	func (s *roomService) GetRoomInfo(req *dto.RoomInfo) (vo.RoomInfo, error) {
		var data po.RoomInfo
		var resp vo.RoomInfo

		_, err := base.XormEngine.Table(po.RoomInfoTB).Where("room_id = ?", 1).Get(&data)
		if err != nil {
			return resp, err
		}
		resp.Data = data
		return resp, nil
	}
*/

func (s *dynamicService) QueryPostAndCountByUserId(req *dto.QueryPostAndCountByUserId) (vo.PostInfoAndCount, error) {
	var resp vo.PostInfoAndCount
	count, err := base.XormEngine.Table(po.PostTable).Where("state=? and user_id = ?", 1, req.UserId).Count(&vo.PostInfo{})
	if err != nil {
		return vo.PostInfoAndCount{}, err
	}
	resp.Count = count
	var data []vo.PostInfo
	err = base.XormEngine.Table(po.PostTable).Select("id,content_text,resource_url,content_type").
		Where("user_id = ?", req.UserId).Limit(5).Desc("created_at").Find(&data)
	if err != nil {
		return vo.PostInfoAndCount{}, err
	}
	if len(data) > 0 {
		resp.Post = data
	} else {
		resp.Post = []vo.PostInfo{}
	}

	return resp, nil
}

// QueryPostAndCountByUserIds 根据批量用户id批量查询动态
func (s *dynamicService) QueryPostAndCountByUserIds(req *dto.QueryPostAndCountByUserIds) ([]vo.PostInfoInUserIds, error) {
	var data []vo.PostInfoInUserIds
	conn := builder.NewCond()
	if req.ContentType != 0 {
		conn = conn.And(builder.Eq{"content_type": req.ContentType})
	}
	conn = conn.And(builder.Eq{"state": 1})
	for _, v := range req.UserId {
		var tempData []vo.PostInfoInUserIds
		var resp []vo.PostInfo
		err := base.XormEngine.Table(po.PostTable).Select("id,content_text,resource_url,content_type").Where(conn).
			Where("user_id = ?", v).Limit(req.PageSize, (req.Page-1)*req.PageSize).Desc("created_at").Find(&resp)
		if err != nil {
			return []vo.PostInfoInUserIds{}, errors.New("获取动态信息失败")
		}
		if len(resp) > 0 {
			tempData = append(tempData, vo.PostInfoInUserIds{UserId: v, PostInfoReCo: resp})
		} else {
			tempData = append(tempData, vo.PostInfoInUserIds{UserId: v, PostInfoReCo: []vo.PostInfo{}})
		}
		data = append(data, tempData...)
	}

	/*err := base.XormEngine.Table(po.PostTable).
		Select("id,user_id,content_text,resource_url,content_type").
		In("user_id", req.UserId).Where(conn).Desc("created_at").Find(&resp)
	if err != nil {
		return , errors.New("获取动态信息失败")
	}*/

	return data, nil
}

// QueryPostDetailByPostId 根据动态id获取动态详情
func (s *dynamicService) QueryPostDetailByPostId(req *dto.QueryPostDetailByPostId) (*vo.PostInfo, error) {
	var resp vo.PostInfo
	_, err := base.XormEngine.Table(po.PostTable).Where("id = ?", req.PostId).Get(&resp)
	if err != nil {
		return nil, errors.New("获取动态信息失败")
	}
	if resp.Id == 0 {
		return nil, nil
	}
	return &resp, nil
}
